import { WeApp } from '../../../common/common';
import { config } from '../../../etc/config';
import httpClient from '../../../common/http-client';
import { ShopCart, ISubmitOrderResult } from '../../../model/order';
import { Consignee } from '../../../model/consignee';
import { IUser } from '../../../model/user';
import tools from '../../../common/tools';
import wxService from '../../../common/wxService';
import utils from '../../../utils/utils';
import { MlcEnum } from '../../../model/enum';
import * as __ from '../../../assets/plugins/underscore.js';
import orderHelper from '../../../utils/orderHelper';

const app = getApp() as WeApp;
interface OrderConfirmPageData {
    btnDisabled?: boolean,
    btnLoading?: boolean,
    carts: {
        items: Array<ShopCart>,
        total: number,
    },
    consignee?: Consignee,
    address?: {
        item?: {},
    },
    orderInfo?: {
        notes?: string,
        goodsInfos?: Array<ShopCart>,
        consignee?: Consignee,
        freightAmount?: number,
        actualTotal?: number
    },
    payCount?: number
}


interface OrderConfirmPage extends IPage {
}

class OrderConfirmPage {
    private freight = {
        goods: 0,
        invoice: 0
    }
    private orderId?: string;
    public data: OrderConfirmPageData = {
        carts: {
            items: [],
            total: 0
        },
        orderInfo: {
            freightAmount: 5
        },
        payCount: 0
    }

    public onLoad(option) {
        const carts = {
            items: wx.getStorageSync('confirmOrder'),
            total: 0,
        }
        carts.items.forEach(n =>
            carts.total += n.unitPrice * n.count
        );
        carts.total = Math.round(carts.total * 100) / 100;
        let sd = {};
        sd['carts'] = carts;
        sd['orderInfo.actualTotal'] = carts.total;
        sd['orderInfo.goodsInfos'] = carts.items.map(val => {
            return {
                goodsId: val.goodsId,
                count: val.count
            };
        });
        this.setData(sd);
    }

    public onShow() {
        let sd = {};
        const consignee = wx.getStorageSync(config.storageNames.confirmOrderConsignee) || wx.getStorageSync(config.storageNames.userInfo).consignee
        if (consignee && __.isObject(consignee)) {
            sd['orderInfo.consignee'] = consignee;
        }
        this.setData(sd);
    }

    bindKeyInput(e){
        if (e.detail.value) {
			let data = {};
			data[`order.notes`] = e.detail.value;
			this.setData(data);
		}
    }

    addOrder(e) {
        const order = this.data.orderInfo;
        if (!order.consignee) {
            utils.showErrorToptips({ msg: '请选择收货地址' });
            return false;
        }
        order['Province'] = order.consignee.areas[0];
        order['City'] = order.consignee.areas[1];
        order['District'] = order.consignee.areas[2];
        order['goodsDesc'] = order.consignee.areas[2];
        wxService.showLoading();
        utils.setBtnStatus(this);
        const res = httpClient.post<ISubmitOrderResult>(config.order.order_create_wx, order)
            .then((res) => {
                wx.removeStorageSync(config.storageNames.confirmOrderConsignee);
                if (res.succeed) {
                    setTimeout(function () {
                        app.addCurUserShopCar(-res.value.shopCarRemoveCount || 0)
                    }, 1);
                    this.orderId = res.value.orderId;
                    orderHelper.wxPayment(res.value, e.detail.formId, (pres) => {
                        utils.showToastText('支付未完成，请重新支付');
                        setTimeout(() => {
                            wxService.redirectTo(tools.buildUrl('/pages/order/detail/index', { id: this.orderId }));
                        }, 800);
                    })
                } else {
                    utils.showToastErr(res.msg);
                }
            })
            .catch(e => {
                utils.showToastErr(e);
            })
        res.then(d => {
            wx.hideLoading();
            utils.setBtnStatus(this);
        })
    }

    setInvoice(e) {
        wxService.navigateTo('../invoice/index');
    }

    changeConsignee(e) {
        wxService.navigateTo('/pages/user/address/list/index',
            {
                cid: this.data.orderInfo.consignee ? this.data.orderInfo.consignee.id : null,
                isSelect: true
            })
    }

    onUnload() {
        wx.removeStorageSync(config.storageNames.confirmOrderConsignee);
    }

}
Page(new OrderConfirmPage());
